package com.dn.lotte.ui.usercenter.activity;

import android.app.DatePickerDialog;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dn.lotte.R;
import com.dn.lotte.api.UserCenterServerApi;
import com.dn.lotte.bean.GroupStatementBean;
import com.dn.lotte.ui.usercenter.adapter.GroupStatementAdapter;
import com.dn.lotte.widget.ClearEditText;
import com.dn.lotte.widget.CustomLoadMoreView;
import com.easy.common.base.BaseActivity;
import com.easy.common.commonwidget.DnToolbar;
import com.easy.common.commonwidget.RippleView;
import com.lzy.okgo.model.HttpParams;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 团队报表（接口对应团队统计）
 * Created by ASUS on 2017/10/12.
 */

public class GroupStatementActivity extends BaseActivity implements
        SwipeRefreshLayout.OnRefreshListener, RippleView.OnRippleCompleteListener, BaseQuickAdapter.RequestLoadMoreListener {

    @Bind(R.id.lt_main_title_left)
    TextView ltMainTitleLeft;
    @Bind(R.id.lt_main_title)
    TextView ltMainTitle;
    @Bind(R.id.lt_main_title_right)
    TextView ltMainTitleRight;
    @Bind(R.id.toolbar)
    DnToolbar toolbar;
    @Bind(R.id.tv_starttime)
    TextView tvStarttime;
    @Bind(R.id.imageView4)
    ImageView imageView4;
    @Bind(R.id.rl_starttime)
    RelativeLayout rlStarttime;
    @Bind(R.id.srl_starttime)
    RippleView srlStarttime;
    @Bind(R.id.tv_overtime)
    TextView tvOvertime;
    @Bind(R.id.rl_overtime)
    RelativeLayout rlOvertime;
    @Bind(R.id.srl_overtime)
    RippleView srlOvertime;
    @Bind(R.id.tv_state)
    TextView tvState;
    @Bind(R.id.rl_start)
    RelativeLayout rlStart;
    @Bind(R.id.srl_state)
    RippleView srlState;
    @Bind(R.id.ll_seek)
    ImageView llSeek;
    @Bind(R.id.et_seek_name)
    ClearEditText etSeekName;
    @Bind(R.id.rl_relative)
    RelativeLayout rlRelative;
    @Bind(R.id.rl_sousuo)
    RelativeLayout rlSousuo;
    @Bind(R.id.rl_statement_list)
    RecyclerView rlStatementList;
    @Bind(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    private int page = 1;
    private List<GroupStatementBean.TableBean> mlist = new ArrayList<>();
    private GroupStatementAdapter groupStatementAdapter;
    private int pagesize = 10;
    private int isRefresh = 0;
    private boolean mLoadMoreEndGone = false;
    private int tag = 0;
    private String[] arr = {
            "全部", "有账变"
    };
    private QMUIListPopup mListPopup;

    @Override
    public int getLayoutId() {
        return R.layout.activitystatementgroup;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        tvState.setText("全部");
        initTitle();
        toolbar.setToolbarLeftBackImageRes(R.drawable.icon_back);
        toolbar.setMainTitle(R.string.agency_group_statement);
        swipeLayout.setOnRefreshListener(this);
        srlStarttime.setOnRippleCompleteListener(this);
        srlOvertime.setOnRippleCompleteListener(this);
        srlState.setOnRippleCompleteListener(this);
        rlStatementList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        groupStatementAdapter = new GroupStatementAdapter(R.layout.item_groupadapter, mlist);
        CustomLoadMoreView customLoadMoreView = new CustomLoadMoreView();
        groupStatementAdapter.setLoadMoreView(customLoadMoreView);
        groupStatementAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        groupStatementAdapter.isFirstOnly(false);
        rlStatementList.setAdapter(groupStatementAdapter);
        isRefresh = 0;
        groupData(page, "", "", "", "");
        // etSeekName.addTextChangedListener(mtextwatcher);//搜索用户监听

    }

  /*  //余额小于监听
    private TextWatcher mtextwatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (tag == 0) {
                groupData(page, "", "", etSeekName.getText().toString().trim(), tvState.getText().toString());
            }
        }
    };*/

    private void groupData(int pag, String starttime, String overtime, String name, String state) {
        String states = "";
        if (state.equals("全部") || state.equals("")) {
            states = "";
        } else {
            states = "1";
        }
        HttpParams params = new HttpParams();
        params.put("page", pag);
        params.put("pagesize", pagesize);
        params.put("d1", starttime);
        params.put("d2", overtime);
        params.put("u", name);
        params.put("tid", states);
        params.put("Id", "");
        getGroupdata(params);
    }


    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.srl_starttime:
                final Calendar c = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(GroupStatementActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        c.set(year, monthOfYear, dayOfMonth);
                        tvStarttime.setText(DateFormat.format("yyy-MM-dd", c));
                        page = 1;
                        if (tvOvertime.getText().toString().equals("结束时间")) {
                            groupData(page, tvStarttime.getText().toString(), "", "", tvState.getText().toString());
                        } else {
                            groupData(page, tvStarttime.getText().toString(), tvOvertime.getText().toString(), "", tvState.getText().toString());
                        }
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
                dialog.show();
                break;
            case R.id.srl_overtime:
                final Calendar c1 = Calendar.getInstance();
                DatePickerDialog dialog1 = new DatePickerDialog(GroupStatementActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        c1.set(year, monthOfYear, dayOfMonth);
                        tvOvertime.setText(DateFormat.format("yyy-MM-dd", c1));
                        page = 1;
                        if (tvStarttime.getText().toString().equals("开始时间")) {
                            groupData(page, "", tvOvertime.getText().toString(), "", tvState.getText().toString());
                        } else {
                            groupData(page, tvStarttime.getText().toString(), tvOvertime.getText().toString(), "", tvState.getText().toString());
                        }
                    }
                }, c1.get(Calendar.YEAR), c1.get(Calendar.MONTH), c1.get(Calendar.DAY_OF_MONTH));
                dialog1.show();
                break;
            case R.id.srl_state:
                initListPopupIfNeed();
                mListPopup.setAnimStyle(QMUIPopup.ANIM_GROW_FROM_LEFT);
                mListPopup.setPreferredDirection(QMUIPopup.DIRECTION_BOTTOM);
                mListPopup.show(rippleView);
                break;
        }
    }

    //获取团队报表数据
    public void getGroupdata(HttpParams params) {
        UserCenterServerApi.getGroupData(params)
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        startProgressDialog();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GroupStatementBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        stopProgressDialog();
                    }

                    @Override
                    public void onNext(@NonNull GroupStatementBean groupStatementBean) {
                        stopProgressDialog();
                        if (groupStatementBean.getResult().equals("1")) {
                            if (groupStatementBean.getTable().size() < pagesize) {
                                mLoadMoreEndGone = true;
                                groupStatementAdapter.loadMoreEnd(mLoadMoreEndGone);
                            }
                            if (isRefresh == 1) {
                                groupStatementAdapter.loadMoreComplete();
                                groupStatementAdapter.addData(groupStatementBean.getTable());
                            } else {
                                mlist = groupStatementBean.getTable();
                                if (swipeLayout != null) swipeLayout.setRefreshing(false);
                                groupStatementAdapter.setNewData(mlist);
                            }
                            if (tag == 1) {
                                tvStarttime.setText("开始时间");
                                tvOvertime.setText("结束时间");
                                etSeekName.setText("");
                                tag = 0;
                            }
                        } else {
                            showShortToast(groupStatementBean.getReturnval());
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        stopProgressDialog();

                    }

                    @Override
                    public void onComplete() {
                        stopProgressDialog();

                    }
                });
    }

//状态选择

    private void initListPopupIfNeed() {
        if (mListPopup == null) {
            final List<String> data = new ArrayList<>();
            for (int i = 0; i < arr.length; i++) {
                data.add(arr[i]);
            }
            ArrayAdapter adapter = new ArrayAdapter<>(mContext, R.layout.simple_list_item, data);
            mListPopup = new QMUIListPopup(mContext, QMUIPopup.DIRECTION_NONE, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(mContext, 80), QMUIDisplayHelper.dp2px(mContext, 220), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    tvState.setText(data.get(i));
                    groupData(1, tvStarttime.getText().toString(), tvOvertime.getText().toString(), "", data.get(i));
                    mListPopup.dismiss();
                }
            });
            mListPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                }
            });
        }
    }

    @Override
    public void onRefresh() {
        page = 1;
        isRefresh = 0;
        tag = 1;
        groupData(page, "", "", "", "");
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        isRefresh = 1;
        groupData(page, "", "", "", "");
    }


    @OnClick(R.id.rl_sousuo)
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_sousuo:
                groupData(page, "", "", etSeekName.getText().toString().trim(), tvState.getText().toString());
                break;
        }

    }
}
